package com.zx.mes.hyl.security.browser;

import com.zx.mes.hyl.security.core.properties.SecurityConstants;
import com.zx.mes.hyl.security.core.properties.SecurityProperties;
import com.zx.mes.hyl.security.core.support.SimpleResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当需要身份验证时，跳转到此进行处理
 * @author hyl
 * @date 2018-5-31
 */
@RestController
public class BrowserSecurityController {

    private static final String END_HTML = ".html";
    private Logger logger = LoggerFactory.getLogger(getClass());

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @RequestMapping(SecurityConstants.DEFAULT_UN_AUTHENTICATION_URL)
    @ResponseStatus(code= HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest != null) {
            String targetUrl = savedRequest.getRedirectUrl();
            logger.info(" 引发跳转的请求是:[{}}",targetUrl);
            if (StringUtils.endsWith(targetUrl, END_HTML)) {
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getSignInPage());
            }
       }

        /* 其它情况直接返回提示 **/
        return new SimpleResponse("访问的服务需要身份认证，请引导用户到登录页");
    }

}
